import Vue from 'vue'
import ViewUI from 'view-design'
import Util from '../libs/util'
import VueRouter from 'vue-router'
import Cookies from 'js-cookie'
import store from '../store'
import { setStore, getStore, removeStore } from "@/config/storage.js"
import { routers, otherRouter, appRouter } from './router'

Vue.use(VueRouter)

// 路由配置
const RouterConfig = {
    routes: routers
}

export const router = new VueRouter(RouterConfig)
// 解决路由重复 报红
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
    ViewUI.LoadingBar.start()
    Util.title(to.meta.title)

    if (Cookies.get('locking') === '1' && to.name !== 'locking') { // 判断当前是否是锁定状态
        next({
            replace: true,
            name: 'locking'
        })
    } else if (Cookies.get('locking') === '0' && to.name === 'locking') {
        next(false)
    } else {
        let token = getStore('token')
        if (!token && to.name !== 'login') { // 判断是否已经登录且前往的页面不是登录页
            next({ name: 'login' })
        } else if (token && to.name === 'login') { // 判断是否已经登录且前往的是登录页
            Util.title()
            next({ name: 'home_index' })
        } else {
            const curRouterObj = Util.getRouterObjByName([otherRouter, ...appRouter], to.name)
            Util.toDefaultPage([...routers], to.name, router, next)
        }
    }
})

router.afterEach((to) => {
    Util.openNewPage(router.app, to.name, to.params, to.query)
    ViewUI.LoadingBar.finish()
    window.scrollTo(0, 0)
});